package cn.opopopo.wordexport.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FileUtil {

    /**
     * 下载文件
     *
     * @param url      url
     * @param filePath filePath
     * @throws IOException
     */
    public static void downloadFile(String url, String filePath) throws IOException {
        try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
             FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            byte[] dataBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param sourceDir   文件
     * @param targetFile 文件
     * @throws IOException
     */
    public static void zipDirectory(String sourceDir, File targetFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(targetFile);
             ZipOutputStream zos = new ZipOutputStream(fos);
             Stream<Path> paths = Files.walk(Paths.get(sourceDir))) {
            paths.filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        try {
                            Path relativePath = Paths.get(sourceDir).relativize(path);
                            ZipEntry zipEntry = new ZipEntry(relativePath.toString());
                            zos.putNextEntry(zipEntry);
                            byte[] buffer = new byte[1024];
                            int length;
                            try (InputStream is = Files.newInputStream(path)) {
                                while ((length = is.read(buffer)) > 0) {
                                    zos.write(buffer, 0, length);
                                }
                            }
                            zos.closeEntry();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        }
    }

    /**
     * @param directory      文件
     */
    public static void deleteFilesInDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteFilesInDirectory(file);
                } else {
                    boolean delete = file.delete();
                    log.info("====delete_file=={},==file=={}", delete, JSONUtil.toJsonPrettyStr(file));
                }
            }
        }
        boolean delete = directory.delete();
        log.info("===delete_file=={},==file=={}", delete,  JSONUtil.toJsonPrettyStr(directory));
    }

    /**
     * 获取文件夹名称
     *
     * @return
     */
    public static String getFileSubstring(String name) {
        if (StrUtil.isBlank(name)) {
            return String.valueOf(System.currentTimeMillis());
        }
        int lastDotIndex = name.lastIndexOf(".");
        if (lastDotIndex != -1) {
            return name.substring(0, lastDotIndex);
        } else {
            return name;
        }
    }
    
    /**
     * 创建临时文件
     */
    public static File createTemplateFile(String fileType) {
        String s = UUID.randomUUID() + "." + fileType;
        String filepath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + File.separator + "temp";
        File dir = new File(filepath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return createSubFile(dir, s);
    }

    /**
     * 创建子文件
     *
     * @param parentDir 父文件夹
     * @param filename  子文件名
     */
    public static File createSubFile(File parentDir, String filename) {
        return new File(parentDir.getAbsolutePath() + File.separator + filename);
    }
}
